import requests
import os
def download_image_to_desktop(url):
    # 手动指定桌面路径（替换成你的实际用户名）
    desktop_path = r"D:\桌面"  # 注意使用原始字符串（r前缀）避免转义问题

    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        # 从URL提取文件名
        filename = url.split('/')[-1]
        file_path = os.path.join(desktop_path, filename)

        # 保存图片
        with open(file_path, 'wb') as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)

        print(f"图片已成功保存到桌面: {file_path}")
        return True

    except Exception as e:
        print(f"下载图片时出错: {e}")
        return False
# 图片URL
image_url = "http://n.sinaimg.cn/news/crawl/117/w550h367/20220417/a3a9-08b2ca6dffe4210149dda424adf0734f.jpg"
# 调用函数下载图片
download_image_to_desktop(image_url)